package springbook.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springbook.model.Result;
import springbook.model.UserInfo;
import springbook.service.UserService;

import static springbook.constant.Constans.USER_SESSION_KEY;

@RequestMapping("/user")
@RestController
public class UserController {
    //用户登陆页面
    @Autowired
    private UserService userService;

    //1.用于验证登录页面，正确则可以成功跳转
    @RequestMapping(value = "/login",produces = "application/json")
    public Result login(String userName, String password, HttpSession session) {
        //1.判空
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) return Result.fail("账号或密码不合法");
        //2.查找用户名对应的对象
        UserInfo userInfo = userService.queryUserInfoByName(userName);
        if(userInfo==null || userInfo.getId()<0) return Result.fail("对象不存在或不合法");
        //3.验证密码正确
        if( !password.equals(userInfo.getPassword())) return Result.fail("账号或密码不正确");
        //4.存取session 这一步有一点不懂
        userInfo.setPassword("666");
        session.setAttribute(USER_SESSION_KEY,userInfo);
        return Result.success("");
    }

}
